chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    // 检测登录状态
    if (msg.action === "checkLoginStatus") {
        (async () => {
            try {
                const { sourceUrl } = msg;
                console.log("检查登录状态:", sourceUrl);
                
                // 发送请求检测是否重定向
                const response = await fetch(sourceUrl, {
                    method: 'GET',
                    credentials: 'include', // 包含cookies
                    redirect: 'manual' // 手动处理重定向
                });
                
                console.log("响应状态:", response.status, response.type);
                
                // 状态码判断
                if (response.status === 401 || response.status === 403) {
                    sendResponse({ 
                        loggedIn: false, 
                        reason: `未授权访问 (${response.status})`
                    });
                    return;
                }
                
                // 检测重定向
                if (response.type === 'opaqueredirect' || response.status === 0) {
                    sendResponse({ 
                        loggedIn: false, 
                        reason: '检测到重定向，可能需要登录'
                    });
                    return;
                }
                
                // 302/301重定向
                if (response.status >= 300 && response.status < 400) {
                    const location = response.headers.get('Location');
                    console.log("重定向到:", location);
                    
                    // 判断是否跳转到登录页
                    if (location && (
                        location.includes('login') || 
                        location.includes('signin') || 
                        location.includes('auth')
                    )) {
                        sendResponse({ 
                            loggedIn: false, 
                            reason: '重定向到登录页'
                        });
                        return;
                    }
                }
                
                // 200状态，检查是否有session cookie
                const cookies = await chrome.cookies.getAll({ url: sourceUrl });
                const sessionCookieNames = ['JSESSIONID', 'SESSION', 'session', 'token', 'auth', 'sid', 'connect.sid'];
                const hasSessionCookie = cookies.some(cookie => 
                    sessionCookieNames.some(name => cookie.name.toLowerCase().includes(name.toLowerCase()))
                );
                
                if (!hasSessionCookie) {
                    sendResponse({ 
                        loggedIn: false, 
                        reason: '未找到session cookie'
                    });
                    return;
                }
                
                sendResponse({ loggedIn: true });
                
            } catch (err) {
                console.error("检查登录状态出错:", err);
                sendResponse({ 
                    loggedIn: false, 
                    reason: `检测失败: ${err.message}`
                });
            }
        })();
        return true;
    }
    
    if (msg.action === "copyCookies") {
        (async () => {
            try {
                const { sourceUrl, targetUrl } = msg;
                
                console.log("开始复制 cookies...");
                console.log("源地址:", sourceUrl);
                console.log("目标地址:", targetUrl);
                
                const cookies = await chrome.cookies.getAll({ url: sourceUrl });
                console.log(`找到 ${cookies.length} 个 cookies`);

                if (cookies.length === 0) {
                    sendResponse({ 
                        success: false, 
                        error: `源地址没有找到任何cookie，可能未登录`,
                        needLogin: true 
                    });
                    return;
                }

                // 检查是否有常见的session cookie
                const sessionCookieNames = ['JSESSIONID', 'SESSION', 'session', 'token', 'auth', 'sid', 'connect.sid'];
                const hasSessionCookie = cookies.some(cookie => 
                    sessionCookieNames.some(name => cookie.name.toLowerCase().includes(name.toLowerCase()))
                );

                if (!hasSessionCookie) {
                    console.warn('警告：未找到常见的session cookie，可能已登录失效');
                    // 继续执行，但在响应中标记
                    sendResponse({ 
                        success: false, 
                        error: `未找到session相关cookie，请确认是否已登录`,
                        needLogin: true,
                        cookieCount: cookies.length
                    });
                    return;
                }

                let copied = 0;
                let errors = [];
                
                for (const cookie of cookies) {
                    try {
                        // 提取目标URL的协议
                        const isTargetHttps = targetUrl.startsWith('https://');
                        
                        // 在目标地址写入 cookie，保留原始属性
                        const cookieData = {
                            url: targetUrl,
                            name: cookie.name,
                            value: cookie.value,
                            path: cookie.path || "/",
                            // 如果目标是http，secure必须为false；如果目标是https，保留原始值
                            secure: isTargetHttps ? cookie.secure : false,
                            // 保留原始httpOnly属性
                            httpOnly: cookie.httpOnly,
                            sameSite: cookie.sameSite || "no_restriction",
                            // 如果有过期时间，也保留
                            ...(cookie.expirationDate && { expirationDate: cookie.expirationDate })
                        };
                        
                        console.log(`正在复制 cookie: ${cookie.name}`, cookieData);
                        const result = await chrome.cookies.set(cookieData);
                        
                        if (result) {
                            copied++;
                            console.log(`✓ 成功复制: ${cookie.name}`);
                        } else {
                            console.warn(`✗ 复制失败: ${cookie.name}`);
                            errors.push(`${cookie.name}: 设置失败`);
                        }
                    } catch (cookieErr) {
                        console.error(`复制 cookie "${cookie.name}" 时出错:`, cookieErr);
                        errors.push(`${cookie.name}: ${cookieErr.message}`);
                    }
                }

                if (copied > 0) {
                    const msg = errors.length > 0 
                        ? `成功${copied}个，失败${errors.length}个. 错误: ${errors.join('; ')}`
                        : `成功复制${copied}个cookies`;
                    
                    // 格式化cookies信息
                    const cookieDetails = cookies.map(c => ({
                        name: c.name,
                        value: c.value.length > 50 ? c.value.substring(0, 50) + '...' : c.value,
                        domain: c.domain,
                        path: c.path,
                        httpOnly: c.httpOnly,
                        secure: c.secure,
                        sameSite: c.sameSite,
                        expirationDate: c.expirationDate ? new Date(c.expirationDate * 1000).toLocaleString('zh-CN') : '会话期'
                    }));
                    
                    sendResponse({ success: true, count: copied, message: msg, cookies: cookieDetails });
                } else {
                    sendResponse({ success: false, error: `所有cookie复制失败: ${errors.join('; ')}` });
                }
            } catch (err) {
                console.error("复制 cookie 总体错误:", err);
                sendResponse({ success: false, error: err.message });
            }
        })();
        return true; // 异步响应
    }
});
